package com.core.controller;

import com.core.domain.DTO.GlhStadiumInfoDTO;
import com.core.domain.DTO.LoginUserInfoDTO;
import com.core.domain.DTO.LygStadiumDTO;
import com.core.domain.DTO.StadiumDTO;
import com.core.domain.Stadium;
import com.core.domain.User;
import com.core.domain.UserTmp;
import com.core.domain.useStadium;
import com.core.service.GlhService;
import com.core.service.LygService;
import com.core.service.PylService;
import com.core.service.TmhService;
import com.core.util.PasswordEncoding;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/common")
@CrossOrigin(origins = {"http://localhost:8080", "http://localhost:63343"})
public class CommonController {

    @Resource
    private LygService lygService;

    @Autowired
    private GlhService glhService;

    @Resource
    private TmhService tmhService;

    @Resource
    private PylService pylService;


//    @PostMapping("/update")
//    public void updateUser(@ModelAttribute User user) {
//        lygService.update(user);
//    }

    @PostMapping("/Update")
    public String update(HttpServletRequest request,User user) {
        user.setId((Integer)request.getSession().getAttribute("userId"));
        if(user.getGender().equals("female")){
            user.setGender("1");
        }else{
            user.setGender("0");
        }
        System.out.println("Update: " + user.toString());
        lygService.update(user);
        return "true";
    }
    /**
     * 下载场馆预约信息
     *
     * @return 场馆预约信息
     * @throws UnsupportedEncodingException
     */
    @GetMapping("/DownLoadAllStadiums")
    public ResponseEntity<byte[]> DownLoadAllStadiums() throws UnsupportedEncodingException {
        List<StadiumDTO> stadiumDTOList = new ArrayList<>();
        //获取所有场馆基础信息
        List<LygStadiumDTO> stadiums = lygService.selectAllStadium();
        for (Stadium stadium : stadiums) {
            StadiumDTO stadiumDTO = new StadiumDTO();
            BeanUtils.copyProperties(stadium, stadiumDTO);
            Integer id = stadium.getId();
            int count = lygService.countById(id);
            stadiumDTO.setCount(count);
            stadiumDTOList.add(stadiumDTO);
        }
        String csvString = tmhService.convertToCsvStadium(stadiumDTOList);

        // 设置响应头信息，告诉浏览器该文件需要被下载
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", "Stadium.csv");

        // 将 CSV 字符串转化为字节数组，并构建 ResponseEntity 对象
        return new ResponseEntity<>(csvString.getBytes("GBK"), headers, HttpStatus.OK);
    }

    /**
     * 下载场地收入情况  --对应api：http://localhost:8080/stadium/djs/getTimeMoney
     *
     * @return
     * @throws UnsupportedEncodingException
     */
    @PostMapping("/downLoadStadiumIncome")
    public ResponseEntity<byte[]> downLoadStadiumIncome(HttpServletRequest request) throws IOException {
        String jsonString = request.getReader().readLine();
        Gson gson = new Gson();
        Map<String, Integer> userNumbers = gson.fromJson(jsonString, new TypeToken<Map<String, Integer>>() {
        }.getType());
        String csvString = tmhService.convertToCsvStadiumIncome(userNumbers);
        // 设置响应头信息，告诉浏览器该文件需要被下载
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", "stadiumAndIncome.csv");
        // 将 CSV 字符串转化为字节数组，并构建 ResponseEntity 对象
        return new ResponseEntity<>(csvString.getBytes("GBK"), headers, HttpStatus.OK);
    }

    /**
     * 下载场馆的每个年龄所占的比例
     *
     * @return
     * @throws UnsupportedEncodingException
     */
    @PostMapping("/downLoadStadiumAge")
    public ResponseEntity<byte[]> downLoadStadiumAge(HttpServletRequest request) throws IOException {
        String jsonString = request.getReader().readLine();
        Gson gson = new Gson();
        List<Map<String, Object>> stadiumAndAgeList = gson.fromJson(jsonString, new TypeToken<List<Map<String, Object>>>() {
        }.getType());
        System.out.println(stadiumAndAgeList);
        System.out.println(stadiumAndAgeList);
        if (stadiumAndAgeList == null) {
            stadiumAndAgeList = new ArrayList<Map<String, Object>>();
        }
        String csvString = tmhService.convertToCsvStadiumAndAge(stadiumAndAgeList);
        // 设置响应头信息，告诉浏览器该文件需要被下载
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", "stadiumAndAge.csv");
        // 将 CSV 字符串转化为字节数组，并构建 ResponseEntity 对象
        return new ResponseEntity<>(csvString.getBytes("GBK"), headers, HttpStatus.OK);
    }

    /**
     * 下载场馆在男性和女性之间的欢迎程度
     *
     * @return
     * @throws UnsupportedEncodingException
     */
    @PostMapping("/downLoadStadiumPopular")
    public ResponseEntity<byte[]> downLoadStadiumPopular(HttpServletRequest request) throws IOException {
        String jsonString = request.getReader().readLine();
        Gson gson = new Gson();
        List<Map<String, Object>> stadiumAndPopularList = gson.fromJson(jsonString, new TypeToken<List<Map<String, Object>>>() {
        }.getType());
        String csvString = tmhService.convertToCsvStadiumAndPopular(stadiumAndPopularList);
        // 设置响应头信息，告诉浏览器该文件需要被下载
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", "stadiumAndPopular.csv");
        // 将 CSV 字符串转化为字节数组，并构建 ResponseEntity 对象
        return new ResponseEntity<>(csvString.getBytes("GBK"), headers, HttpStatus.OK);
    }

    /**
     * 下载场馆使用人数
     *
     * @return
     * @throws UnsupportedEncodingException
     */
    @PostMapping("/downLoadStadiumUserNumbers")
    public ResponseEntity<byte[]> downLoadStadiumUserNumbers(HttpServletRequest request) throws IOException {

        String jsonString = request.getReader().readLine();
        Gson gson = new Gson();
        Map<String, Integer> userNumbers = gson.fromJson(jsonString, new TypeToken<Map<String, Integer>>() {
        }.getType());
        String csvString = tmhService.convertToCsvStadiumUserNumbers(userNumbers);
        // 设置响应头信息，告诉浏览器该文件需要被下载
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", "stadiumUseNumbers.csv");
        // 将 CSV 字符串转化为字节数组，并构建 ResponseEntity 对象
        return new ResponseEntity<>(csvString.getBytes("GBK"), headers, HttpStatus.OK);
    }

    /**
     * 场馆利用率下载
     *
     * @param request
     * @return
     * @throws IOException
     */
    @PostMapping("/downLoadStadiumUtilizationRate")
    public ResponseEntity<byte[]> downLoadStadiumUtilizationRate(HttpServletRequest request) throws IOException {
        String jsonString = request.getReader().readLine();
        Gson gson = new Gson();
        Map<String, String> stadiumUtilizationRate = gson.fromJson(jsonString, new TypeToken<Map<String, String>>() {
        }.getType());
        String csvString = tmhService.convertToCsvStadiumUtilizationRate(stadiumUtilizationRate);
        // 设置响应头信息，告诉浏览器该文件需要被下载
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", "stadiumUtilizationRate.csv");
        // 将 CSV 字符串转化为字节数组，并构建 ResponseEntity 对象
        return new ResponseEntity<>(csvString.getBytes("GBK"), headers, HttpStatus.OK);
    }

    /**
     * 下载查询场馆预约信息
     *
     * @param name
     * @return
     * @throws IOException
     */
    @PostMapping("/downLoadQueryStadium")
    public ResponseEntity<byte[]> downLoadQueryStadium(String name) throws IOException {
        System.out.println(name);
        HashMap<useStadium, Integer> information = new HashMap<>();
        List<useStadium> list = pylService.quaryStdiumStatus(name);
        int count = 0;
        for (useStadium usestadium : list) {
            information.put(usestadium, count);
            count++;
            //            System.out.println(usestadium);
        }
        String csvString = tmhService.convertToCsvQueryStadium(information);
        // 设置响应头信息，告诉浏览器该文件需要被下载
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", "queryStadium.csv");
        // 将 CSV 字符串转化为字节数组，并构建 ResponseEntity 对象
        return new ResponseEntity<>(csvString.getBytes("GBK"), headers, HttpStatus.OK);
    }

    /**
     * 根据名字下载场馆信息
     *
     * @param
     * @return
     * @throws IOException
     */
    @PostMapping("/downLoadQueryStadiumByName")
    public ResponseEntity<byte[]> downLoadQueryStadiumByName(String name) throws IOException {
//            Stadium stadium = (Stadium)request.getAttribute("stadiumInfo");
        System.out.println(name);
        Stadium stadium = pylService.queryStadiumInfo(name);
        String csvString = tmhService.convertToCsvQueryStadiumByName(stadium);
        // 设置响应头信息，告诉浏览器该文件需要被下载
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", "queryStadiumByName.csv");
        // 将 CSV 字符串转化为字节数组，并构建 ResponseEntity 对象
        return new ResponseEntity<>(csvString.getBytes("GBK"), headers, HttpStatus.OK);
    }

    @PostMapping("/downLoadQueryUserInfo")
    public ResponseEntity<byte[]> downLoadQueryUserInfo(String userAccount) throws IOException {
        User user = pylService.quaryUserInfo(userAccount);
        String csvString = tmhService.convertToCsvQueryUserInfo(user);
        // 设置响应头信息，告诉浏览器该文件需要被下载
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", "queryUserInfo.csv");
        // 将 CSV 字符串转化为字节数组，并构建 ResponseEntity 对象
        return new ResponseEntity<>(csvString.getBytes("GBK"), headers, HttpStatus.OK);
    }

    /**
     * 用户修改密码
     *
     * @param oldPassword
     * @param newPassword
     * @return
     */
    @GetMapping("/modifyPassword")
    public boolean modifyPassword(String oldPassword, String newPassword, HttpServletRequest request) {
        System.out.println("修改密码..." + oldPassword + "→" + newPassword);
        Integer userId = (Integer) request.getSession().getAttribute("userId");
        User user = tmhService.selectUserById(userId);
        String previousPassword = user.getUserPassword();

        newPassword = PasswordEncoding.encrypt(newPassword);
        oldPassword = PasswordEncoding.encrypt(oldPassword);
        if (!previousPassword.equals(oldPassword)) {
            return false;
        }
        if (oldPassword != null && newPassword != null) {
            tmhService.modifyPassword(userId, newPassword);
            return true;
        }
        return false;
    }

    @GetMapping("/logOut")
    public void logOut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getSession().removeAttribute("userId");
//        request.getRequestDispatcher("/usermanagement_page/login.html").forward(request,response);
//        response.sendRedirect("http://localhost:8080/stadium/usermanagement_page/login.html");
    }

    /**
     * 用户注册
     * @param request
     * @param response
     * @throws IOException
     */
    @PostMapping("/register")
    public int userRegister(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("1111");
        String jsonString = request.getReader().readLine();
        System.out.println(jsonString);
        // 使用Jackson将JSON对象字符串转换为Java对象
        ObjectMapper objectMapper = new ObjectMapper();
        LoginUserInfoDTO userTmp = objectMapper.readValue(jsonString, LoginUserInfoDTO.class);
        //System.out.println(userTmp);
        System.out.println(userTmp.getUserAccount());
        System.out.println(userTmp.getUserPassword());
        System.out.println(userTmp.getEmail());
        System.out.println(userTmp.getPhone());
        System.out.println(userTmp.getGender());
        System.out.println(userTmp.getAge());
        if (userTmp.getGender().equals("男") || userTmp.getGender().equals("0")) {
            userTmp.setGender("0");
        } else {
            userTmp.setGender("1");
        }
        //加盐
        String tmp = userTmp.getUserPassword();
        userTmp.setUserPassword(PasswordEncoding.encrypt(tmp));

        if (glhService.addUserByLoginUserInfoDTO(userTmp) == true) {
            //添加成功
            System.out.println("添加成功");

            return 1;
        } else {
            //添加失败，此处默认为数据库中用户名重复
            System.out.println("寄，用户名重复");
            return 0;
        }

    }

    /**
     * 用户登录
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    @PostMapping("/login")
    public int userLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1. 校验
        String userAccount, userPassword;
        System.out.println("1111");
        String jsonString = request.getReader().readLine();
        System.out.println(jsonString);
        // 使用Jackson将JSON对象字符串转换为Java对象
        ObjectMapper objectMapper = new ObjectMapper();
        UserTmp userTmp = objectMapper.readValue(jsonString, UserTmp.class);
        String json = objectMapper.writeValueAsString(userTmp);
        System.out.println(userTmp.getUserAccount());
        System.out.println(userTmp.getUserPassword());
        userAccount = userTmp.getUserAccount();
        userPassword = userTmp.getUserPassword();
//        User userTmp = new User();
//        response.getWriter().write(json);
//        userAccount = request.getParameter("username");
//        userPassword = request.getParameter("password");

        String tmp = userTmp.getUserPassword();
        System.out.println(PasswordEncoding.encrypt(tmp));
        userTmp.setUserPassword(PasswordEncoding.encrypt(tmp));

        if (userAccount.equals("") || userPassword.equals("")) {
            System.out.println("1111");
            return 0;
        }
        if (userAccount.length() < 3) {
            System.out.println("22222");
            return 0;
        }
        if (userPassword.length() < 3) {
            System.out.println("333333");
            return 0;

        }
        // 账户不能包含特殊字符
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            return 0;
        }
        // 2. 加密

        // 查询用户是否存在
        User queryWrapper = new User();
        queryWrapper.setUserAccount(userAccount);
        queryWrapper.setUserPassword(userTmp.getUserPassword());
        User user = glhService.queryUser(queryWrapper);
        // 用户不存在
        if (user == null) {
            System.out.println("5555");
            return 0;
            // request.getRequestDispatcher("/stadium/usermanagement_page/register.html").forward(request,response);
        } else {
            System.out.println("66666");
            System.out.println(user);
            request.getSession().setAttribute("userId", user.getId());

            if(user.getUserRole() == 1){
                return 1;
            }
            else{
                return 2;
            }
            // response.sendRedirect("/stadium/lyg");
            //request.getRequestDispatcher("http://localhost:8080/stadium/reservation_page/reserveStadiumStatus.jsp").forward(request,response);

        }
//        return user;
    }
}





